import React, { useState, useEffect } from 'react';
import { connect } from 'umi';
import { useRequestPowerAfterInit } from '@/hooks/useRequestPowerAfterInit';
import { TjContent, TjFilter, TjHeader, TjUpload } from '@/tjComponents';
import { Button, Checkbox, Drawer, message, Modal, Pagination, Select, Spin } from 'antd';
import TjMarketingUnit from '@/tjComponents/TjMarketingUnit';
import type { ProvinceType, StationType } from '@/hooks/useRequestPowerAfterInit';
import { useSetState } from 'ahooks';
import {
  addStationInfo,
  delStationInfo,
  exportList,
  getStationList,
  getTemplateUrl,
  importList,
  queryBaseGroupList,
  stationAddressList,
  stationTypeList,
  updateStationInfo,
} from './services';
import { HttpCode } from '#/utils/contacts.js';
import _ from 'lodash';
import './index.less';
import TjTable from '../components/TjTable';
import { getColumns } from './helper';
import DrawerContent from './components/DrawerContent';
import moment from 'moment';
import { useForm } from 'antd/es/form/Form';
import { UploadOutlined } from '@ant-design/icons';
import { downloadFileForFront } from '@/tjComponents/TjUpload/TjUploadContent';
import { features, useTablePipeline } from 'ali-react-table';

const { confirm } = Modal;

const StationInfo: React.FC<IStationInfoProps> = (props) => {
  const [marketInfo, setMarketMarketInfo] = useState<any>({});
  const { initLoading, province, errorMsg, treeData } = useRequestPowerAfterInit(
    `/power/dataPower/common/${props.menuCode}/t_station`,
    (parmas) => {
      const { label, value } = parmas;
      setMarketMarketInfo({ marketId: value, marketName: label });
      const data = {
        marketId: value,
        stationIdList: parmas.stations.map((v: StationType) => v.stationId),
      };
      setDefaultValues(data);
      setReq(data);
    },
    {
      convertResult: '2',
      matchFirst: 0,
    },
  );
  const [defaultValues, setDefaultValues] = useState<any>({});
  const [loading, setLoading] = useState<boolean>(false);
  const [req, setReq] = useSetState<any>({
    currentPage: 1,
    pageSize: 20,
  });
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [editDefaultValue, setEditDefaultValue] = useState<any>();
  const [visible, setVisible] = useState<boolean>(false);
  const [stationTypes, setStationTypes] = useState<any[]>([]);
  const [stationLocations, setStationLocations] = useState<any[]>([]);
  const [btnLoading, setBtnLoading] = useState<boolean>(false);
  const [canExport] = useState<boolean>(
    props.buttonPermissions.some((item) => item.menuCode === props.menuCode),
  );
  const [form] = useForm();
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
  const [pagination, setPagination] = useSetState({
    pageSize: 0,
    total: 0,
    currentPage: 0,
  });
  const [groupList, setGroupList] = useState<any[]>([]);

  const changeProvince = (val: string) => {
    const item = _.find(province, (n: ProvinceType) => n.value === val);
    if (item) {
      form.setFieldsValue({ stationIdList: item.stations.map((v: StationType) => v.stationId) });
      setMarketMarketInfo({ marketId: item.value, marketName: item.label });
    }
  };

  const onSearch = (values: any) => {
    setReq({
      ...values,
      currentPage: 1,
    });
  };

  const onReset = (values: any) => {
    if (values.marketId !== marketInfo.marketId) {
      changeProvince(values.marketId);
    }
    setReq({
      ...values,
      currentPage: 1,
    });
  };

  const pageChange = (pageNumber: number, pageSize?: number) => {
    setReq({ currentPage: pageNumber, pageSize });
  };

  const del = (record: any) => {
    confirm({
      title: '确定删除此行数据吗？',
      onOk: () => {
        delStationInfo(record.stationId).then((res: any) => {
          if (res.statusCode && res.statusCode === HttpCode.SUCCESS) {
            message.success('删除成功');
            setReq({
              currentPage: 1,
              refresh: moment().valueOf(),
            });
          } else {
            message.error('系统异常');
          }
        });
      },
    });
  };

  const edit = (row: any) => {
    const data = {
      ...row,
      stationLocation: [row.provinceId, row.cityId],
    };
    setEditDefaultValue(data);
    setVisible(true);
  };

  const add = () => {
    setVisible(true);
  };

  const onSubmit = (data: any) => {
    setBtnLoading(true);
    let fn = () => addStationInfo(data);
    if (editDefaultValue) {
      fn = () => updateStationInfo(data);
    }
    fn()
      .then((res: any) => {
        if (res) {
          if (res.statusCode && res.statusCode === HttpCode.SUCCESS) {
            message.success(editDefaultValue ? '修改成功' : '新增成功');
            onClose();
            setReq({
              currentPage: 1,
              refresh: moment().valueOf(),
            });
          } else {
            message.error(
              editDefaultValue
                ? `修改失败：${res.data.join(',')}`
                : `新增失败：${res.data.join(',')}`,
            );
          }
        } else {
          message.error('系统异常');
        }
      })
      .finally(() => {
        setBtnLoading(false);
      });
  };

  const onClose = () => {
    setEditDefaultValue(null);
    setVisible(false);
  };

  const exportData = () => {
    if (!canExport) {
      message.warning('请联系管理员获取相关权限');
      return;
    }
    const list =
      selectedRowKeys && selectedRowKeys.length > 0
        ? selectedRowKeys
        : form.getFieldValue('stationIdList');
    exportList(list).then((res) => {
      if (res) {
        downloadFileForFront(res, `场站基础信息_${moment().format('YYYY-MM-DD')}.xlsx`);
      }
    });
  };

  const changeTableCheckbox = (values: any[]) => {
    setSelectedRowKeys(values);
  };

  const query = () => {
    setLoading(true);
    getStationList(req)
      .then((res) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          const records = _.get(res, 'data.records', []);
          setDataSource(records);
          setPagination({
            total: res.data.total,
            pageSize: res.data.size,
            currentPage: res.data.current,
          });
        } else {
          message.error(res.message);
          setDataSource([]);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const getStationTypeList = () => {
    stationTypeList().then((res) => {
      if (res.statusCode === HttpCode.SUCCESS) {
        const data = _.get(res, 'data', []);
        if (data && data.length > 0) {
          setStationTypes(
            data.map((v: any) => ({
              value: v.stationTypeId,
              label: v.stationTypeName,
            })),
          );
        }
      } else {
        message.error(res.message);
      }
    });
  };

  const getStationAddressList = () => {
    stationAddressList().then((res) => {
      if (res.statusCode === HttpCode.SUCCESS) {
        const data: any[] = _.get(res, 'data', []);
        if (data && data.length > 0) {
          const newArr = data.map((v) => {
            let children = [];
            if (v.children && v.children.length > 0) {
              children = v.children.map((v: any) => {
                return {
                  label: v.cityName,
                  value: v.cityId,
                };
              });
            }

            return {
              label: v.provinceName,
              value: v.provinceId,
              children,
            };
          });
          setStationLocations(newArr);
        }
      } else {
        message.error(res.message);
      }
    });
  };

  const getCompany = () => {
    queryBaseGroupList().then((res: any) => {
      if (res.statusCode === HttpCode.SUCCESS) {
        const data: any[] = _.get(res, 'data', []);
        if (data && data.length > 0) {
          // setGroupList(data);
          const newData = data.map((v) => {
            return {
              label: v.groupCompanyName,
              value: v.groupId,
              groupName: v.groupName,
            };
          });
          setGroupList(newData);
        }
      } else {
        message.error(res.message);
      }
    });
  };

  useEffect(() => {
    getStationTypeList();
    getStationAddressList();
    getCompany();
  }, []);

  useEffect(() => {
    if (req.stationIdList && req.stationIdList.length > 0) {
      query();
    }
  }, [req]);

  const pipeline = useTablePipeline({
    components: { Checkbox },
  })
    .input({ columns: getColumns({ edit, del }), dataSource: dataSource })
    .primaryKey('stationId')
    .use(
      features.multiSelect({
        value: selectedRowKeys,
        highlightRowWhenSelected: true,
        checkboxPlacement: 'start',
        checkboxColumn: { lock: true },
        clickArea: 'cell',
        onChange: changeTableCheckbox,
      }),
    );

  return (
    <div className="stationinfo">
      <TjHeader
        left={
          <TjFilter
            form={form}
            defaultValues={defaultValues}
            items={[
              {
                name: 'marketId',
                render: (
                  <Select
                    options={province}
                    style={{ width: 180 }}
                    loading={initLoading}
                    onChange={changeProvince}
                  />
                ),
              },
              {
                name: 'stationIdList',
                render: <TjMarketingUnit treeData={treeData} marketId={marketInfo.marketId} />,
              },
            ]}
            onSearch={onSearch}
            onReset={onReset}
            loading={loading || initLoading}
          />
        }
        right={
          <div className="header-opt">
            <TjUpload
              loading={loading || initLoading}
              uploadUrl={importList}
              uploadSuccessCb={() => {
                setReq({
                  currentPage: 1,
                  refresh: moment().valueOf(),
                });
              }}
              accept=".xls, .xlsx"
              downloadTemplate={{
                templateName: '场站基础信息导入模板.xlsx',
                url: getTemplateUrl,
              }}
            />
            <Button
              type="link"
              icon={<UploadOutlined />}
              loading={loading || initLoading}
              onClick={exportData}
            >
              导出
            </Button>
          </div>
        }
      />
      <TjContent
        titleLeft="场站基础信息管理"
        titleRight={
          <Button
            type="primary"
            style={{ width: 98 }}
            onClick={add}
            loading={loading || initLoading}
          >
            新增
          </Button>
        }
      >
        <div className="box">
          <div className="table">
            <TjTable {...pipeline.getProps()} isLoading={loading} />
          </div>
          <div className="pagination-box">
            <Pagination
              size="small"
              showSizeChanger
              showQuickJumper
              onChange={pageChange}
              total={pagination.total}
              showTotal={(total) => `共 ${total} 条`}
              pageSize={pagination.pageSize}
              current={pagination.currentPage}
            />
          </div>
        </div>
      </TjContent>
      <Drawer
        title={editDefaultValue ? '编辑' : '新增'}
        placement="right"
        onClose={onClose}
        visible={visible}
        width="1164px"
        destroyOnClose
      >
        <DrawerContent
          stationTypes={stationTypes}
          province={province}
          stationLocations={stationLocations}
          groupList={groupList}
          defaultValue={editDefaultValue}
          onSubmit={onSubmit}
          loading={btnLoading}
        />
      </Drawer>
    </div>
  );
};

interface IStationInfoProps {
  menuCode: string;
  buttonPermissions: any[];
}

export default connect(({ global }: any) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(StationInfo);
